<?php

namespace app\admin\model;

use think\Model;

use think\Db;
use think\Request;

class Sale_pay_cheque extends Model
{
    public function getsalecheque($res)
    {
        $page = $res['page'];
        $limit = $res['pageSize'];
        //查找条件
        $mapwhere = $this->statuswhere($res['status']);
        $join = [
            ['sale b', 'a.sale_id=b.id', 'LEFT'],//销售表
            ['cheque_used c', 'a.used_id=c.id', 'LEFT'],//使用说明表
        ];
        $saledata = Db::name('sale_pay_cheque')->alias('a')->join($join)->where($mapwhere)->field('a.*,b.id as saleid,b.co_id,b.co_branch_id,b.saler_id,c.remark')->page($page, $limit)->select();
        //对数据进行处理
        $time = 604800;//取消按钮只能显示7天
        foreach ($saledata as $saledatakey => $saledataval) {
            //公司名称
            $saledata[$saledatakey]['company_name'] = getinfo($saledataval['co_id'], 'company')['name'];
            //业务员
            $saledata[$saledatakey]['saler_name'] = getinfo($saledataval['saler_id'], 'admin')['nickname'];
            //编辑时间和编辑人
            $saledata[$saledatakey]['managename'] = getinfo($saledataval['update_id'], 'admin')['nickname'];
            $saledata[$saledatakey]['update_date'] = getTimeDate($saledataval['update_at'], 12);
            //通过付款登记id，获取类型id
            $paytype_id=getValue('sale_payreg',['id'=>$saledataval['sale_payreg_id']],'paytype_id');
            //付款方式
            $pay_typewhere['mkey'] = 'sale_pay_type_' .$paytype_id;
            $saledata[$saledatakey]['paytype_name'] = getlangname('multi_lang', $pay_typewhere, $res['lang']);
            //开户行
            if ($saledataval['bank_id']) {
                $co_bank = getinfo($saledataval['bank_id'], 'co_bank');
                $saledata[$saledatakey]['bank_name'] = getinfo($co_bank['banks_id'], 'banks')['name'];//开票银行
            } else {
                $saledata[$saledatakey]['bank_name'] = '';
            }

            //付款日期
            $saledata[$saledatakey]['pay_day_date'] = getTimeDate($saledataval['pay_day'], 15);
            //签收人和签收时间
            $saledata[$saledatakey]['got_name'] = getinfo($saledataval['got_id'], 'admin')['nickname'];
            $saledata[$saledatakey]['got_date'] = getTimeDate($saledataval['got_at'], 12);

            //存入日期
            if ($saledataval['checkin_day'] > 0) {
                $checkin_time = $saledataval['checkin_day'] + $time;//最终可操作的时间撮(7天)
                if (time() <= $checkin_time) {
                    $saledata[$saledatakey]['sevenday'] = '1';
                }
                $saledata[$saledatakey]['checkin_date'] = getTimeDate($saledataval['checkin_day'], 12);
            }
            //设置存入的账号
            if ($saledataval['accounts_id'] > 0) {
                //表示有存入
                $account_info = getinfo($saledataval['accounts_id'], 'accounts');
                $accontbankname = getinfo($account_info['banks_id'], 'banks')['name'];
                $strnum = substr($account_info['account_num'], 0, 3) . '***' . substr($account_info['account_num'], 7);
                $saledata[$saledatakey]['accountnumber'] = $accontbankname . '/' . $strnum;//存入账号
                $saledata[$saledatakey]['accountname'] = $account_info['bankname'];
            }

            //使用日期
            if ($saledataval['used_day'] > 0) {
                $used_time = $saledataval['used_day'] + $time;//最终可操作的时间撮(7天)
                if (time() <= $used_time) {
                    $saledata[$saledatakey]['sevendays'] = '1';
                }
                $saledata[$saledatakey]['used_date'] = getTimeDate($saledataval['used_day'], 12);
            }
            //确认者和确认时间
            $saledata[$saledatakey]['check_name'] = getinfo($saledataval['check_id'], 'admin')['nickname'];
            if ($saledataval['success_at'] > 0) {
                $saledata[$saledatakey]['class'] = 'green';
                $saledata[$saledatakey]['success_fail_date'] = getTimeDate($saledataval['success_at'], 12);
            } else if ($saledataval['fail_at'] > 0) {
                $saledata[$saledatakey]['class'] = 'red';
                $saledata[$saledatakey]['success_fail_date'] = getTimeDate($saledataval['fail_at'], 12);
            } else {
                $saledata[$saledatakey]['success_fail_date'] = '';
                $saledata[$saledatakey]['class'] = '';
            }
        }

        $count = Db::name('sale_pay_cheque')->alias('a')->join($join)->where($mapwhere)->count();
        $ids = array_column($saledata, 'id');
        //处理每一个标签的数字
        $arrcount = $this->arrcount($join, $res['status']);
        return array('count' => $count, 'data' => $saledata, 'ids' => $ids,'arrcount'=>$arrcount);
    }

    //显示每一个标签的数字
    protected function arrcount($join, $status)
    {
        $reswhereone = $this->statuswhere(1);
        $reswheretwo = $this->statuswhere(2);
        $reswherethree = $this->statuswhere(3);
        $one =  $count = Db::name('sale_pay_cheque')->alias('a')->join($join)->where($reswhereone)->count();
        $two = $count = Db::name('sale_pay_cheque')->alias('a')->join($join)->where($reswheretwo)->count();
        $three =  $count = Db::name('sale_pay_cheque')->alias('a')->join($join)->where($reswherethree)->count();
        return array(
            'one' => $one == 0 ? '' : $one,
            'two' => $two == 0 ? '' : $two,
            'three' => $three == 0 ? '' : $three,
        );
    }

    //设置条件
    public function statuswhere($status)
    {
        $mapsale = array();
        $mapsale['a.got_at'] = array('gt', 0);//获得支票的时间大于0
        switch ($status) {
            //新支票
            case '1':
                $mapsale['a.checkin_day'] = 0;//没有存入日期
                $mapsale['a.used_day'] = 0;//没有使用日期
                break;
            //已存入
            case '2':
                $mapsale['a.checkin_day'] = array('gt', 0);//表示已存入账号了
                break;
            //已使用
            case '3':
                $mapsale['a.used_day'] = array('gt', 0);//表示已使用说明了
                break;
        }
        return $mapsale;
    }

    //设置确认存入账户和确认使用
    public function savecheque($res)
    {
        $ids = array_column($res['datatop'], 'id');//需要更改的支票id
        $map['id'] = ['in', $ids];
        $insert['create_id'] = $insert['update_id'] = $update['update_id'] = session('userid');
        $insert['create_at'] = $insert['update_at'] = $update['update_at'] = time();
        if ($res['code'] == 1) {
            //确认存入
            if (!$res['account_id']) {
                return array('msg' => '请选择要存入的账号', 'status' => 2);
            }
            $update['accounts_id'] = $res['account_id'];//存入账号
            $update['checkin_day'] = time();//存入日期
            $upid = Db::name('sale_pay_cheque')->where($map)->update($update);
        } elseif ($res['code'] == 2) {
            //确认使用
            $usedarr = getables('sale_pay_cheque', $map, 'used_id,id');
            $used_ids = array_unique(array_column($usedarr, 'used_id'));
            foreach ($used_ids as $used_idskey => $used_idsval) {
                if ($used_idsval == 0) {
                    unset($used_ids[$used_idskey]);
                }
            }
            $mapuse['id'] = ['in', $used_ids];
            //删除对应的使用说明表
            Db::name('cheque_used')->where($mapuse)->delete();
            //改变支票表
            $resupdate = Db::name('sale_pay_cheque')->where($map)->update(['used_day' => 0, 'used_id' => 0]);
            if ($resupdate !== false) {
                //对数据进行重新的写入
                foreach ($usedarr as $usedarrkey => $usedarrval) {
                    if ($res['textremark']) {
                        //使用说明添加
                        $insert['remark'] = $res['textremark'];
                        $cheque_usedid = Db::name('cheque_used')->insertGetId($insert);
                        //更新支票表
                        $update['used_id'] = $cheque_usedid;
                        $update['used_day'] = time();
                        Db::name('sale_pay_cheque')->where('id', $usedarrval['id'])->update($update);
                    } else {
                        //没有填写使用说明
                        $update['used_day'] = time();
                        //更新支票登记表
                        Db::name('sale_pay_cheque')->where('id', $usedarrval['id'])->update($update);
                    }
                }
            }
        }
        return array('msg' => '编辑成功', 'status' => 1);
    }

    //已存入 已使用中的取消
    public function chequequxiao($res, $code)
    {
        //如果已经付款登记了就不能取消
        $infocheque = getinfo($res['id'], 'sale_pay_cheque');
        //表示会计已经确认了，无法取消
        if ($infocheque['check_id'] > 0) {
            return array('msg' => '该支票已经付款登记了，无法取消', 'status' => 2);
        }
        $update['update_id'] = session('userid');
        $update['update_at'] = time();
        if ($code == 1) {
            //已存入 取消
            $update['accounts_id'] = $update['checkin_day'] = 0;
            $resupadminid = Db::name('sale_pay_cheque')->where('id', $res['id'])->update($update);
        } elseif ($code == 2) {
            //已使用 取消
            Db::name('cheque_used')->where('id', $infocheque['used_id'])->delete();
            $update['used_id'] = $update['used_day'] = 0;
            $resupadminid = Db::name('sale_pay_cheque')->where('id', $res['id'])->update($update);
        }
        if ($resupadminid !== false) {
            return array('status' => 1, 'msg' => lang("edited_successfully"));
        } else {
            return array('status' => 0, 'msg' => lang("edit_failed"));
        }

    }

    //已存入中的确认和退票
    public function chequequeren($res, $code)
    {
        //这里的需要改变付款登记表中数据
        $sale_payinfo = Db::name('sale_pay_cheque')->field('sale_payreg_id')->where('id', $res['id'])->find();
        $update['check_id'] = session('userid');
        if ($code == 1) {
            //确认呢
            $update['success_at'] = time();
            $update['fail_at'] = 0;
            Db::name('sale_payreg')->where('id', $sale_payinfo['sale_payreg_id'])->update($update);
            $resupid = Db::name('sale_pay_cheque')->where('id', $res['id'])->update($update);
            $success = '确认成功';
            $faile = '确认失败';
        } else {
            //退票
            $update['fail_at'] = time();
            $update['success_at'] = 0;
            Db::name('sale_payreg')->where('id', $sale_payinfo['sale_payreg_id'])->update($update);
            $resupid = Db::name('sale_pay_cheque')->where('id', $res['id'])->update($update);
            $success = '退票成功';
            $faile = '退票失败';
        }
        if ($resupid !== false) {
            return array('status' => 1, 'msg' => $success);
        } else {
            return array('status' => 0, 'msg' => $faile);
        }
    }

    //存入账户 使用 数据接口
    public function accountcheque($res, $code)
    {
        $map['a.id'] = array('in', $res['id']);
        $join = [
            ['sale b', 'a.sale_id=b.id', 'LEFT'],//销售表
        ];
        $data = Db::name('sale_pay_cheque')->alias('a')->where($map)->join($join)->field('a.*,b.id as saleid,b.co_id,b.co_branch_id')->select();
        $summoney = 0;//合计
        $arr = array();
        foreach ($data as $datakey => $dataval) {
            if (in_array($dataval['sale_id'], $arr)) {
                $data[$datakey]['sale_id'] = '';
            }
            array_push($arr, $dataval['sale_id']);
            //公司名称
            $data[$datakey]['company_name'] = getinfo($dataval['co_id'], 'company')['name'];
            //付款日期
            $data[$datakey]['pay_day_date'] = getTimeDate($dataval['pay_day'], 15);
            //签收人和签收时间
            $data[$datakey]['got_name'] = getinfo($dataval['got_id'], 'admin')['nickname'];
            $data[$datakey]['got_date'] = getTimeDate($dataval['got_at'], 12);
            $summoney += $dataval['amount'];
        }

        if ($code == 1) {
            //设置存入的账户
            $admindata = session('admin');
            $admin_id = $admindata['id'];
            if ($admindata['position_id'] != 1) {
                //获取支付账号
                $whereacc[] = ["exp", "FIND_IN_SET($admin_id,admin_ids)"];
            }
            //收款账号
            $whereacc[] = ["exp", "FIND_IN_SET('1',is_payment)"];

            $whereacc['a.is_public'] = 1;//是否公开
            $whereacc['a.country_id'] = 1;//国家
            //支付账号
            $accountname = Db::name('accounts')->alias('a')->join('nt_banks b', 'a.banks_id=b.id', 'left')->field('a.id,a.bankname,a.account_num,a.is_main,b.name')->where($whereacc)->select();
        } else {
            $accountname = '';
        }
        $resdata['data'] = $data;
        $resdata['count'] = Db::name('sale_pay_cheque')->alias('a')->where($map)->join($join)->count();
        $resdata['summoney'] = $summoney;
        return array('topdata' => $resdata['data'], 'count' => $resdata['count'], 'summoney' => $resdata['summoney'], 'accounts' => $accountname);
    }
}